module Utils
  module Search
    protected
      def self.or_search_conditions(fields, values)
        rvalue = []
        val_array = split_search_values(values)
        val_array.each do |val|
          fvalue = []
          fields.each do |field|
            fvalue << "lower(#{field}) like lower('%#{ActiveRecord::Base.q(val)}%')"
          end
          rvalue << fvalue.join(" or ")
        end
        rvalue.join(" and ")
      end

      def self.split_search_values(values)
        rvalue = []
        phrase = ""
        is_phrase = false
        values = cleanup_search_values(values)
        values.split(' ').each do |val|
          if val =~ /^"/
            is_phrase = true
            rvalue << val.gsub('"','') if val =~ /"$/
            phrase = val.gsub('"','')
            next
          end

          if is_phrase && !(val =~ /"$/)
            phrase += " " + val
          else
            rvalue << val
          end

          if val =~ /"$/
            is_phrase = false
            phrase += " " + val.chop
            rvalue << phrase
            phrase = ""
          end
        end
        rvalue
      end

      def self.cleanup_search_values(values)
        values = values.gsub('"','') if (values.count('"') % 2) != 0
        values
      end

  end
end
